const formidable = require("formidable");
const path = require("path");
const fs = require("fs");

// 获取表单数据
const getFormData = req => {
	return new Promise((resolve, reject) => {
		const form = new formidable.IncomingForm();
		form.encoding = "utf-8"; // 编码
		form.keepExtensions = true; // 保留扩展名
		form.uploadDir = path.join(__dirname, "../public/"); //文件存储路径 最后要注意加 '/' 否则会被存在public下

		form.parse(req, (err, fields, files) => {
			if (err) {
				reject(err);
				return;
			}
			resolve(files.file);
		});
	});
};

const uploadFile = async req => {
	try {
		const file = (await getFormData(req))[0];
		const oldPath = file.filepath;
		const ext = file.originalFilename.split(".").pop();
		const imgName =
			new Date().getTime() + "-" + file.newFilename + "." + ext;
		const newPath = path.join(__dirname, "../public/" + imgName);

		fs.renameSync(oldPath, newPath);

		return imgName;
	} catch (err) {
		console.error(err);
		return "";
	}
};

const getDistance = (lat1, lng1, lat2, lng2) => {
	let rad1 = (lat1 * Math.PI) / 180.0;
	let rad2 = (lat2 * Math.PI) / 180.0;
	let a = rad1 - rad2;
	let b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
	let r = 6378137;
	return (
		r *
		2 *
		Math.asin(
			Math.sqrt(
				Math.pow(Math.sin(a / 2), 2) +
					Math.cos(rad1) *
						Math.cos(rad2) *
						Math.pow(Math.sin(b / 2), 2)
			)
		)
	);
};

const getClientIP = ctx => {
	let ip =
		ctx.headers["x-forwarded-for"] ||
		ctx.ip ||
		ctx.connection.remoteAddress ||
		ctx.socket.remoteAddress ||
		ctx.connection.socket.remoteAddress ||
		"";
	if (ip.split(",").length > 0) {
		ip = ip.split(",")[0];
	}
	return ip;
};

module.exports = {
	uploadFile,
	getDistance,
	getClientIP,
};
